/*********************************************************************************
 *      Copyright:  (C) 2023 Lin XinCheng
 *                  All rights reserved.
 *
 *       Filename:  chrdevAPP.c
 *    Description:  This file for chrdev.c app.
 *                 
 *        Version:  1.0.0(2023年07月15日)
 *         Author:  Lin XinCheng <1481155734@qq.com>
 *      ChangeLog:  1, Release initial version on "2023年07月15日 23时18分52秒"
 *                 
 ********************************************************************************/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

/* 
 * ./chrdevAPP -w abc
 * ./chrdevApp -r
 * */
int main(int argc,char **argv)
{
	int  fd;
	char buf[1024];
	int  len;

	/* 1.判断参数 */
	if( argc <2 )
	{
		printf("Usage :%s -w <string>\n",argv[0]);
		printf("	   %s -r\n",argv[0]);
		return -1;
	}

	/* 2.打开文件 */
	fd = open("/dev/chrdev",O_RDWR);
	if( fd == -1 )
	{
		printf("can't open file /dev/hello\n");
		return -1;
	}

	/* 3.写文件或者读文件 */
	if(( 0 == strcmp(argv[1], "-w")) && (argc == 3))
	{
		len = strlen(argv[2]) + 1;
		len = len < 1024 ? len : 1024;
		write(fd, argv[2], len);
	}
	else if( (0 ==strcmp(argv[1], "-r")) && (argc == 2))
	{
		len = read(fd, buf, 1024);
		buf[1024] = '\0';
		printf("APP read : %s\n",buf);
	}
	else{
		printf("Usage : %s -w <string>\n",argv[0]);
		printf("		%s -r \n",argv[0]);
		return -1;
	}

	close(fd);
	return 0;
}

